//
//  PackParse.m
//  KangarooDoctor
//
//  Created by gang on 2024/2/8.
//

#import "PackParse.h"
#import "Pack.h"PackParse
#import "Crc8.h"

int readCBParam(const uint8_t *buffer, int buflen, struct CBParam *p)
{
    uint8_t *curr = buffer;

    curr += readBYTE(curr, &p->highPress);
    curr += readBYTE(curr, &p->lowPress);
    curr += readBYTE(curr, &p->heartBeat);
    
    return curr - buffer;
}

int readCCParam(const uint8_t *buffer, int buflen, struct CCParam *p)
{
    uint8_t *curr = buffer;

    curr += readBYTE(curr, &p->systolic);
    curr += readBYTE(curr, &p->diastolic);
    curr += readBYTE(curr, &p->pulse);
    curr += readBYTE(curr, &p->heartAnomaly);
    
    return curr - buffer;
}

//int readPayload(const BYTE *buffer, int buflen, struct CCPayload *p)
//{
//
//}

int readWrap(const uint8_t *buffer, int buflen, struct Wrap *wrap)
{
//    if ( buflen < 8 ) {
//        return @"buf len less than 8";
//    }
    
    //check crc
    uint8_t u = CRC8(buffer, buflen);
    uint8_t tail =buffer[buflen-1];
    if (u != tail) {
        printf("crc fail\n");
//        return 0;
//        return @"crc fail";
    }else{
//        printf("crc ok\n");
    }
    
    uint8_t *curr = buffer;
    
    curr += readUINT16(curr, &wrap->type);
    curr +=readBYTE(curr, &wrap->payloadLen);
    
    if (wrap->type == WrapTypeReadFromPort) {
        
        struct PortPayload *pp = malloc(sizeof(struct PortPayload));
        curr +=readBYTE(curr, &pp->cmd);
        if (pp->cmd == 0xCB) {
            //实时数据
            
            struct CBParam *param = malloc(sizeof(struct CBParam));
            curr += readCBParam(curr, buflen - 4, param);
            
            printf("实时数据: high: %u, low: %d, heart beat: %d\n",
                   param->highPress,
                   param->lowPress,
                   param->heartBeat);
            pp->param = param;
            
        }else if(pp->cmd == 0xCC){
            
            //测量结果, 对实时数据的统计
            struct CCParam *p = malloc(sizeof(struct CCParam));
            curr += readCCParam(curr, buflen - 4, p);
            
            printf("s: %u, d: %u, p:%u, a: %d\n",
                   p->systolic,
                   p->diastolic,
                   p->pulse,
                   p->heartAnomaly);
            
            pp->param = p;
        }
        
        wrap->payload = pp;
    }
    
//    curr += wrap->payloadLen;
    
    curr += readBYTE(curr, &wrap->check);
 
    return curr - buffer;
}

void checkWrap(struct Wrap *w)
{
}

@implementation PackParse
+(void)test
{
//    uint8_t buf[] = {0xD0, 0xC2, 0x05, 0xCC, 0x04, 00, 00, 00,  0x43};
//    uint8_t buf[] = {0xD0, 0xC2, 0x04 , 0xCB, 0x00, 0x64, 0x01, 0x92};
    uint8_t buf[] = {0xD0, 0xC2, 0x05, 0xCC, 0xB4, 0x5E, 0x4C, 0x00, 0xC5};
    
    struct Wrap *wrap = malloc(sizeof(struct Wrap));
    readWrap(buf, sizeof(buf), wrap);
}
@end
